﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Collections.Generic;

namespace BlogBackUp
{
    public partial class BlogBackUp : Form
    {
        #region Members
        private String blogHomePage = "";
        private int pages = 0;
        private String savePath = "";
   
        private WebBrowser webBrowser = new WebBrowser();
        private event DefaultAdressEventHandler defaultAdress;
        private event DownloadAdressEventHandler downloadAdress;  
        private System.Collections.Specialized.StringCollection allArticles = new System.Collections.Specialized.StringCollection();
        private int currentArticleNum = 0;
        #endregion

        #region Constructor and deconstructor
        public BlogBackUp()
        {
            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;          

            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);

        //this.listView1.Columns.Add("ArticleAdress", this.listView1.Width);

        }
        #endregion

        #region webbrowser completed event and domain combox index changed event
        void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (handleState == HandleState.AllAdresses)
            {
                // Handle current default adress
                int currentAdressesCount = 0;
                HtmlDocument htmlDoc = ((WebBrowser)sender).Document;

                ArrayList tempAdresses = HtmlUtils.GetAdressesByDefaultHtmlDocument(htmlDoc,domain,userName);
                currentAdressesCount = tempAdresses.Count;

                currentDefaultAdressIndex++;
                // adresses count is greater than 0, raise DefaultAdressEventHandler event
                if (currentAdressesCount > 0)
                {
                    foreach (String str in tempAdresses)
                    {
                        if (!AllAdresses.Contains(str))
                        {
                            AllAdresses.Add(str);
                            this.listView1.Items.Add(new ListViewItem(str));
                        }
                    }
                    defaultAdress(null, new DefaultAdressEventArgs(currentDefaultAdressIndex));
                    //BlogBackUp_defaultAdress(null, new DefaultAdressEventArgs(currentDefaultAdressIndex));
                }
                else
                { 
                    if (defaultAdress != null)
                        defaultAdress -= this.BlogBackUp_defaultAdress;                   
                   
                   isGetDefaultAdressesCompleted = true;
                   this.AllArticleLabel.Text += "completed!";
                   //MessageBox.Show("Get all articles completed!");
                   //Completed defaultAdressCompletedForm = new Completed();
                   //defaultAdressCompletedForm.StrForCompletedButton = "Get all articles completed!";
                   //defaultAdressCompletedForm.Show();
                }
            }
            else if (handleState == HandleState.DownloadFiles)
            {
                // download current page's files

                ArrayList refFileList = new ArrayList();
                HtmlDocument htmlDoc = ((WebBrowser)sender).Document;
                String htmlFile = HtmlUtils.FindContentHtmlFile(htmlDoc);

                if (isNeedDownloadRefFiles)
                {
                    // step 1
                    // get Img files
                    HtmlUtils.GetImgFileList(htmlDoc, savePath + needDownloadFileRelativePath, ref refFileList);
                    // step 2
                    // get css file
                    RefFile cssFile = new RefFile();
                    HtmlUtils.GetCssFile(htmlFile, savePath + needDownloadFileRelativePath, ref cssFile);
                    refFileList.Add(cssFile);
                    // step 3
                    // delete no needed to download files
                    DownloadUtils.DeleteNoNeededRefFile(ref refFileList, htmlFile);
                    // step 4
                    // fix path for downloaded files
                    DownloadUtils.FixRefFilePath(ref refFileList, ref htmlFile);
                    // step 5
                    // download ref files
                    DownloadUtils.DownloadRefFiles(refFileList, savePath + needDownloadFileRelativePath);
                }
                // step 6
                // save html file
                DownloadUtils.DownloadHtmlFile(htmlDoc.Title + ".html", savePath, htmlFile);
                this.progressBar1.Increment(1);               
                this.NowHandleLabel.Text = "Now handle file is:" + AllAdresses[currentDefaultAdressIndex];
                this.NowHandleLabel.Update();

                currentDownloadAdress++;
                // if there are some pages need to download, raise download event
                if (currentDownloadAdress < AllAdresses.Count)
                {
                    downloadAdress(null, new DownloadAdressEventArgs((String)AllAdresses[currentDownloadAdress]));
                    //BlogBackUp_downloadAdress(null, new DownloadAdressEventArgs((String)AllAdresses[currentDownloadAdress]));
                }
                if (currentDownloadAdress == AllAdresses.Count)
                {
                    MessageBox.Show("Back up completed!");
                }
            }
            
        }               
        #endregion

        #region Get all articles operation
        private void GetAllArticles_Click(object sender, EventArgs e)
        {
            // For test
            //currentDefaultAdressIndex = 11;

            userName = UserNameTextBox.Text;

            handleState = HandleState.AllAdresses;

            defaultAdress += this.BlogBackUp_defaultAdress;

            //BlogBackUp_defaultAdress(null, new DefaultAdressEventArgs(currentDefaultAdressIndex));
            defaultAdress(null, new DefaultAdressEventArgs(currentDefaultAdressIndex));
        }

       private void ConstructIndexPage(int index)
       {
           String defaultAdress = blogHomePage + "/"+ @"default.html?page=" + index.ToString();

           webBrowser.Navigate(defaultAdress);
       }
       #endregion

        #region backup operation
        private void BackUp_Click(object sender, EventArgs e)
        {  
            
            if (AllAdresses.Count > 0 && isGetDefaultAdressesCompleted)
            {
                downloadAdress += new DownloadAdressEventHandler(BlogBackUp_downloadAdress);

                handleState = HandleState.DownloadFiles;

                //BlogBackUp_downloadAdress(null, new DownloadAdressEventArgs((String)AllAdresses[currentDownloadAdress]));
                downloadAdress(null, new DownloadAdressEventArgs((String)AllAdresses[currentDownloadAdress]));
            }
        }

       private void BlogBackUp_downloadAdress(object sender, DownloadAdressEventArgs e)
       {
           // navigate to the adress
           webBrowser.Navigate(e.Adress);
       }
        #endregion

        private void BrowserButton_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folerDialog = new FolderBrowserDialog();
            if (DialogResult.OK == folerDialog.ShowDialog())
            {
                savePath = folerDialog.SelectedPath +"\\";
                savePathTextBox.Text = savePath;
            }
        }
    }
}